package com.johnson.news;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

import android.Manifest;
import android.app.Notification;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.Toast;

import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.johnson.news.activity.AskMeComplaintNoticeActivity;
import com.johnson.news.activity.FragmentContainerActivity;
import com.johnson.news.activity.MyAskListActivity;
import com.johnson.news.databinding.ActivityMainBinding;
import com.johnson.news.event_msg.SwitchAskMenuVisibleMsg;
import com.johnson.news.fragment.AskFragment;
import com.johnson.news.fragment.HomeFragment;
import com.johnson.news.fragment.SearchFragment;
import com.johnson.news.fragment.SettingFragment;
import com.johnson.news.fragment.WebViewFragment;
import com.johnson.news.util.Utils;
import com.johnson.news.view.CommonListPopupWindow;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youmbe.library.BaseBindingActivity;
import com.youmbe.library.util.RxjavaUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import static com.johnson.news.activity.FragmentContainerActivity.action_search;

public class MainActivity extends BaseBindingActivity<ActivityMainBinding> {
    View bottomTabArray[];
    Fragment fragmentArray[];

    AskFragment askFragment;

    FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Utils.getScreenWH(this);
        Utils.initSerializeData(this);

        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_SETTINGS)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
//                        if(!permission.granted && permission.name.equals(Manifest.permission.WRITE_SETTINGS)) {
//
//                            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
////                                if(!Settings.System.canWrite(activityInstance)){
//                                    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
//                                            Uri.parse("package:" + activityInstance.getPackageName()));
//                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                    startActivityForResult(intent, 111);
////                                }else{
////                                }
//                            }
//                        } else
                        if (permission.granted && permission.name == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                            Utils.checkUpdate(activityInstance, true);
                        }
                    }
                });

        startBaiduPush();

//        EventBus.getDefault().register(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 111) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void init() {
        fragmentManager = getSupportFragmentManager();

        bottomTabArray = new View[]{
                dataBinding.mainBottomTab1,
                dataBinding.mainBottomTab2,
                dataBinding.mainBottomTab3,
                dataBinding.mainBottomTab4,
                dataBinding.mainBottomTab5,
        };

        fragmentArray = new Fragment[bottomTabArray.length];

        dataBinding.setOnClickListener(onClickListener);

        onSelectTab(0);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return doubleClickToExit();
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    void startBaiduPush() {
        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
                Utils.BAIDU_PUSH_APPKEY);


        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
                R.layout.notification_custom_builder,
                R.id.notification_icon,
                R.id.notification_title,
                R.id.notification_text);

        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
        cBuilder.setNotificationDefaults(Notification.DEFAULT_VIBRATE);
        cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
        cBuilder.setLayoutDrawable(R.drawable.simple_notification_icon);
        cBuilder.setNotificationSound(Uri.withAppendedPath(
                MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "6").toString());
        // 若您的应用需要适配Android O（8.x）系统，且将目标版本targetSdkVersion设置为26及以上时：
        // 可自定义channelId/channelName, 若不设置则使用默认值"Push"；
        // 注：非targetSdkVersion 26的应用无需以下2行调用且不会生效
        cBuilder.setChannelId("testId");
        cBuilder.setChannelName("testName");
        // 推送高级设置，通知栏样式设置为下面的ID，ID应与server下发字段notification_builder_id值保持一致
        PushManager.setNotificationBuilder(this, 1, cBuilder);
    }

    int clickTimes = 0;

    boolean doubleClickToExit() {
        if (clickTimes == 0) {
            clickTimes++;
            Toast.makeText(this, "再点一次退出", Toast.LENGTH_SHORT).show();
            Observable.timer(2, TimeUnit.SECONDS)
                    .subscribeOn(RxjavaUtil.io())
                    .observeOn(RxjavaUtil.ui())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            clickTimes = 0;
                        }
                    });
        } else {
            finish();
        }

        return true;
    }

    int currentIndex = 0;

    void onSelectTab(int index) {
//        dataBinding.mainAskMore.setVisibility(View.GONE);
        boolean clickSameTab = currentIndex == index;
        currentIndex = index;
        for (int i = 0; i < bottomTabArray.length; i++) {
            View selectView = bottomTabArray[i];
            if (index == i) {
                selectView.setSelected(true);
                if (selectView instanceof RadioButton) {
                    ((RadioButton) selectView).setChecked(true);
                    ((RadioButton) selectView).setTextColor(getResources().getColor(R.color.colorPrimary));
                }
            } else {
                selectView.setSelected(false);
                if (selectView instanceof RadioButton) {
                    ((RadioButton) selectView).setChecked(false);
                    ((RadioButton) selectView).setTextColor(getResources().getColor(R.color.text_color_2));
                }
            }

        }

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment currentFragment = fragmentArray[index];

        for (int i = 0; i < bottomTabArray.length; i++) {
            if (fragmentArray[i] != null) {
                fragmentTransaction.hide(fragmentArray[i]);
            }
        }

        if (currentFragment == null) {
            if (index == 0) {
                currentFragment = HomeFragment.newInstance(null, null);
            } else if (index == 1) {
                currentFragment = new WebViewFragment("http://jyt.shaanxi.gov.cn/mob/h5/appgongkai.html");//http://jyt.shaanxi.gov.cn/mob/wenwoba/appgongkai.html
            } else if (index == 2) {
                currentFragment = new WebViewFragment("http://jyt.shaanxi.gov.cn/mob/h5/wenwoba.html");//http://www.snedu.gov.cn/mob/wenwoba/wenwoba.html
            } else if (index == 3) {
                currentFragment = AskFragment.newInstance(null, null);
                askFragment = (AskFragment) currentFragment;
            } else if (index == 4) {
                currentFragment = SettingFragment.newInstance(null, null);
            }

            fragmentArray[index] = currentFragment;

            fragmentTransaction.add(R.id.main_content_layout, currentFragment);
        } else {
            fragmentTransaction.show(currentFragment);
            fragmentTransaction.setMaxLifecycle(currentFragment, Lifecycle.State.RESUMED);

            if(currentFragment instanceof HomeFragment && clickSameTab) {
                HomeFragment homeFragment = (HomeFragment) currentFragment;
                homeFragment.refreshCurrentPage();
            }
        }

        fragmentTransaction.commitAllowingStateLoss();

    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(v.getId() == R.id.main_bottom_tab1 || v.getId() == R.id.main_search) {
                dataBinding.mainSearch.setVisibility(View.VISIBLE);
            } else {
                dataBinding.mainSearch.setVisibility(View.GONE);
            }
            switch (v.getId()) {
                case R.id.main_bottom_tab1:
                    onSelectTab(0);
                    dataBinding.mainTitle.setText(R.string.logo_name);
                    break;
                case R.id.main_bottom_tab2:
                    onSelectTab(1);
                    dataBinding.mainTitle.setText(R.string.main_tab_title_2);
//                    if(askFragment.needShowMenu()) {
//                        dataBinding.mainAskMore.setVisibility(View.VISIBLE);
//                    } else {
//                        dataBinding.mainAskMore.setVisibility(View.GONE);
//                    }
                    break;
                case R.id.main_bottom_tab3:
                    onSelectTab(2);
                    dataBinding.mainTitle.setText(R.string.main_tab_title_3);
//                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
                    break;
                case R.id.main_bottom_tab4:
                    onSelectTab(3);
                    dataBinding.mainTitle.setText(R.string.main_tab_title_4);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                    break;
                case R.id.main_bottom_tab5:
                    onSelectTab(4);
                    dataBinding.mainTitle.setText(R.string.main_tab_title_5);
                    break;
                case R.id.main_search:
                    Bundle bundle = new Bundle();
                    bundle.putInt(FragmentContainerActivity.intent_key_action, action_search);
                    bundle.putString(FragmentContainerActivity.intent_key_title, getString(R.string.search_title));
                    startActivity(FragmentContainerActivity.class, bundle);
                    break;
//                case R.id.main_ask_more:
//                    ArrayList<String> titleList = new ArrayList<>();
//                    titleList.add(getString(R.string.ask_complaint_of_my));
//                    titleList.add(getString(R.string.ask_complaint_notice));
//                    CommonListPopupWindow popupWindow = new CommonListPopupWindow(activityInstance);
//                    popupWindow.setData(titleList);
//                    popupWindow.initView();
//                    popupWindow.setOnFilterClickListener(new CommonListPopupWindow.OnFilterClickListener() {
//                        @Override
//                        public void onFilterClick(int index) {
//                            if(index == 0) {//我的投诉
//                                startActivity(MyAskListActivity.class, null);
//                            } else {//投诉须知
//                                startActivity(AskMeComplaintNoticeActivity.class, null);
//                            }
//                        }
//                    });
//                    popupWindow.showAsDropDown(dataBinding.mainAskMore);
//                    break;
            }
        }
    };

//    @Subscribe
//    public void switchAskMenuVisible(SwitchAskMenuVisibleMsg msg) {
//        dataBinding.mainAskMore.setVisibility(msg.show ? View.VISIBLE : View.GONE);
//    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }
}
